#!BPY
"""
Name: 'My Mesh Script'
Blender: 243
Group: 'Mesh'
Tooltip: 'This script run on blender 3d'
"""

# licence: GPL v3

from Blender import Scene, Mesh, Window, Draw, sys
import BPyMessages
import bpy

DO_CHISEL = Draw.Create(0) 
DO_SHRINK = Draw.Create(0)

class ModellingTools( ):
	
	def __init__( self ):
		pass
	
	# shrink the selected faces on the mesh 
	def shrink( self, me ):
		for f in me.faces:
			if f.sel:
				c = f.cent
				for v in f:
					v.co = (c+v.co)/2
					
	# chisel 
	def chisel( self, me ):
		groups = me.getVertGroupNames( )
		
		weights = me.getVertexInfluences( 0 )
		
		for influence in weights:
			groupName = influence[0]
			vertsInGroup = me.getVertsFromGroup( groupName )
			
			# reduce each vertex in a group with group weight 
			for v in vertsInGroup:
				me.verts[ v ].co.x *= influence[1]
				me.verts[ v ].co.y *= influence[1]
				me.verts[ v ].co.z *= influence[1]
		
def ui():
	
	global DO_CHISEL, DO_SHRINK
	
	pup_block = [  
		('SHRINK', DO_SHRINK, 'Shrink mesh'),\
		('CHISEL', DO_CHISEL, 'Chisel mesh'),\
	]
	
	if not Draw.PupBlock("Mesh Modelling Tools", pup_block):
		return
		

def my_mesh_util(me):
	# This function runs out of editmode with a mesh
	# error cases are alredy checked for
	
	# Remove these when writing your own tool
	print me.name
	print 'vert count', len(me.verts)
	print 'edge count', len(me.edges)
	print 'face count', len(me.faces)
	
	# Examples
	
	# Move selected verts on the x axis
 	
	"""
	for v in me.verts:
		if v.sel:
			v.co.x *= -0.5
			v.co.y *= -0.5
			v.co.z *= -0.5
	"""

	global DO_CHISEL, DO_SHRINK
	
	tool = ModellingTools( )
	
	if DO_CHISEL.val:
		tool.chisel( me )
	if DO_SHRINK.val:
		tool.shrink( me )
	


def main():
	
	# Gets the current scene, there can be many scenes in 1 blend file.
	sce = bpy.data.scenes.active
	
	# Get the active object, there can only ever be 1
	# and the active object is always the editmode object.
	ob_act = sce.objects.active
	
	if not ob_act or ob_act.type != 'Mesh':
		BPyMessages.Error_NoMeshActive()
		return 
	
	
	# Saves the editmode state and go's out of 
	# editmode if its enabled, we cant make
	# changes to the mesh data while in editmode.
	is_editmode = Window.EditMode()
	if is_editmode: Window.EditMode(0)
	
	Window.WaitCursor(1)
	me = ob_act.getData(mesh=1) # old NMesh api is default
	
	ui() # display ui
	
	t = sys.time()
	
	# Run the mesh editing function
	my_mesh_util(me)
	
	# Restore editmode if it was enabled
	if is_editmode: Window.EditMode(1)
	
	# Timing the script is a good way to be aware on any speed hits when scripting
	print 'My Script finished in %.3f seconds' % (sys.time()-t)
	Window.WaitCursor(0)
	
	
# This lets you can import the script without running it
if __name__ == '__main__':
	main()